

class PersonController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ personInstanceList: Person.list( params ), personInstanceTotal: Person.count() ]
    }

    def show = {
        def personInstance = Person.get( params.id )

        if(!personInstance) {
            flash.message = "Person not found with id ${params.id}"
            redirect(action:list)
        }
        [ personInstance : personInstance ]
    }

    def delete = {
        def personInstance = Person.get( params.id )
        if(personInstance) {
            try {
                personInstance.delete(flush:true)
                flash.message = "Person ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Person ${params.name} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Person not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def personInstance = Person.get( params.id )

        if(!personInstance) {
            flash.message = "Person not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ personInstance : personInstance ]
        }
    }

    def update = {
        def personInstance = Person.get( params.id )
        if(personInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(personInstance.version > version) {
                    
                    personInstance.errors.rejectValue("version", "person.optimistic.locking.failure", "Another user has updated this Person while you were editing.")
                    render(view:'edit',model:[personInstance:personInstance])
                    return
                }
            }
            personInstance.properties = params
            if(!personInstance.hasErrors() && personInstance.save()) {
                flash.message = "Person ${params.name} updated"
                redirect(action:show,id:personInstance.id)
            }
            else {
                render(view:'edit',model:[personInstance:personInstance])
            }
        }
        else {
            flash.message = "Person not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def personInstance = new Person()
        personInstance.properties = params
        return ['personInstance':personInstance]
    }

    def save = {
    	def category = Vcategory.get(params.category.id)
    	def sport = Sport.get(params.sport.id)
        def personInstance = new Person(params)
    	
        if(!personInstance.hasErrors() && personInstance.save()) {
        	(new SportTag([person:personInstance, sport:sport])).save()
        	(new CategoryTag([person:personInstance, category:category])).save()
            flash.message = "Person ${personInstance.name} created"
            redirect(action:show,id:personInstance.id)
        }
        else {
            render(view:'create',model:[personInstance:personInstance])
        }
    }
    
    def upload = {
    	
    }
    
    def download = {
    	
    }
     
    def downloadSubmit = {
    	def people = Person.list()
    	[people:people]
    }
    
    def uploadSubmit = {
    	def file = request.getFile('myFile')
    	if (file) {
    		def inputStream = file.getInputStream()
    		if (inputStream){
    			def br = new BufferedReader(new InputStreamReader(inputStream))
    			def line = br.readLine()
    			def key = line.split(',')
    			
    			def personCount = 0
    			while ((line = br.readLine()) != null) {
    				def tokens = line.split(',')
    				def entity = [:]
    				for (def i = 0; i < tokens.size(); i++) {
    					entity[key[i]] = tokens[i]
    				}
    				//save person
    				def person = Person.findByUid(entity['uid'])
    				if (!person) {
    					person = new Person([uid:entity['uid'] ,name:entity['name'], language:entity['language'], phone:entity['phone'], email:entity['email']])
    				}
    				if(person.save()) {
    					personCount++
	    				person = Person.findByUid(entity['uid'])
	    				def category = Vcategory.findByName(entity['category'])
	    				if (category) {
	    					(new CategoryTag([person:person, category:category])).save()
	    				}
	    				def sport = Sport.findByName(entity['sport'])
	    				if (sport) {
	    					(new SportTag([person:person, sport:sport])).save()
	    				}
    				}
    			}
   				flash.message = personCount + '筆資料上傳成功 '
    		}
    	}
    	redirect(action:upload)
    }
    
    def search = {
    	
    }
    
    def searchSubmit = {
    	def people = Person.findAllByNameLike('%'+ params.searchKey +'%')
    	[people:people]
    }
}
